package com.atjinggu.jinggumail.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atjinggu.jinggumail.common.constant.OrderConstant;
import com.atjinggu.jinggumail.common.enums.OrderStatusEnum;
import com.atjinggu.jinggumail.common.exception.WareStockException;
import com.atjinggu.jinggumail.common.to.SkuHasStockVo;
import com.atjinggu.jinggumail.common.to.mq.OrderTo;
import com.atjinggu.jinggumail.common.to.mq.SeckillOrderTo;
import com.atjinggu.jinggumail.common.utils.R;
import com.atjinggu.jinggumail.common.vo.MemberResponseVo;
import com.atjinggu.jinggumail.order.entity.OrderItemEntity;
import com.atjinggu.jinggumail.order.entity.OrderReturnReasonEntity;
import com.atjinggu.jinggumail.order.entity.PaymentInfoEntity;
import com.atjinggu.jinggumail.order.feign.CartFeignService;
import com.atjinggu.jinggumail.order.feign.MemberFeignService;
import com.atjinggu.jinggumail.order.feign.ProductFeignService;
import com.atjinggu.jinggumail.order.feign.WmsFeignService;
import com.atjinggu.jinggumail.order.interceptor.LoginInterceptor;
import com.atjinggu.jinggumail.order.service.OrderItemService;
import com.atjinggu.jinggumail.order.service.PaymentInfoService;
import com.atjinggu.jinggumail.order.to.OrderCreateTo;
import com.atjinggu.jinggumail.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.rabbitmq.client.Channel;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.omg.IOP.ENCODING_CDR_ENCAPS;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atjinggu.jinggumail.common.utils.PageUtils;
import com.atjinggu.jinggumail.common.utils.Query;

import com.atjinggu.jinggumail.order.dao.OrderDao;
import com.atjinggu.jinggumail.order.entity.OrderEntity;
import com.atjinggu.jinggumail.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Slf4j
@Service("orderService")
@RabbitListener(queues = {"jinggumail-queue"})
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

   @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    
    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    PaymentInfoService paymentInfoService;
    //@RabbitListener(queues = {"jinggumail-queue"})
    @RabbitHandler
    public void receiveMsg(Message message, OrderReturnReasonEntity entity, Channel channel){
        System.out.println("接收到的消息 =》 "+message);
        System.out.println("接收到的消息entity =》 "+entity);
        //channel内按顺序自增的 例1、2、3、3、5...
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //手动签收，非批量提交ACK
        try {
            if(deliveryTag % 2 ==0) {
                //签收
                //deliveryTag  -> 队内顺序, boolean multiple  -> 是否批量
                channel.basicAck(deliveryTag, false);
            }else {
                //deliveryTag  -> 队内顺序, boolean multiple -> 是否批量, boolean requeue -> 重新入队，还是直接丢弃
                channel.basicNack(deliveryTag,false,false);
                //deliveryTag  -> 队内顺序, boolean requeue -> 重新入队，还是直接丢弃
                //basicReject与basicNack基本一致，只是少了批量提交的功能，所以我们一般使用basicNack
                //channel.basicReject();
            }
        }catch (Exception e){
           log.error("宕机了===");
        }

    }
    @RabbitHandler
    public void receiveMsg(Message message, OrderEntity entity, Channel channel){
        System.out.println("接收到的消息 =》 "+message);
        System.out.println("接收到的消息entity =》 "+entity);

    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo orderConfirm() throws ExecutionException, InterruptedException {
        MemberResponseVo member = LoginInterceptor.loginUser.get();
        if(null  == member){
            return null;
        }
        OrderConfirmVo orderConfirm = new OrderConfirmVo();
        //主线程中获取attrs
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        //1.查询收货地址列表
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //子线程中塞入attrs
            RequestContextHolder.setRequestAttributes(attrs);
            List<OrderConfirmVo.MemberAddressVo> address = memberFeignService.orderReceiveAddress(member.getId().toString());
            orderConfirm.setAddress(address);
        }, executor);

        //2. 查询选中购物项
        CompletableFuture<Void> orderItem = CompletableFuture.supplyAsync(() -> {
            RequestContextHolder.setRequestAttributes(attrs);
            List<OrderConfirmVo.OrderItemVo> items = cartFeignService.OrderItemList();
            orderConfirm.setItems(items);
            return items;
        }, executor).thenAcceptAsync((items) -> {
            List<Long> collect = items.stream().map(item -> Long.parseLong(item.getSkuId())).collect(Collectors.toList());
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            List<OrderConfirmVo.OrderHasStock> data = skusHasStock.getData(new TypeReference<List<OrderConfirmVo.OrderHasStock>>() {
            });
            Map<Long, Boolean> collects = data.stream().collect(Collectors.toMap(OrderConfirmVo.OrderHasStock::getSkuId, OrderConfirmVo.OrderHasStock::getHasStock));
            orderConfirm.setHasStock(collects);
        });

        //设置令牌
        String orderToken = UUID.randomUUID().toString().replace("_","");
        redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX+member.getId(),orderToken,30, TimeUnit.MILLISECONDS);
        orderConfirm.setOrderToken(orderToken);
        //3.查询用户积分
        orderConfirm.setIntegration(member.getIntegration());
        //其他数据自动计算
         CompletableFuture.allOf(addressFuture,orderItem).get();
        return orderConfirm;
    }

    //@GlobalTransactional
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public OrderSubmitRespVo orderSubmit(OrderSubmitVo vo) {
        OrderSubmitRespVo respVo = new OrderSubmitRespVo();
        MemberResponseVo member = LoginInterceptor.loginUser.get();
        String redisKey = OrderConstant.ORDER_TOKEN_PREFIX + member.getId();
        //令牌校验
        String script = "if  redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long res = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(redisKey), vo.getOrderToken());
        if(res == 0l){
            //校验失败
            respVo.setCode(1);
            return respVo;
        }else {
            OrderCreateTo to = createOrder();
            //保存订单
            saveOrder(to);

            //锁库存
            WareSkuLockVo lockVo = new WareSkuLockVo();
            lockVo.setOrderSn(to.getOrder().getOrderSn());
            List<WareSkuLockVo.WareOrder> collect = to.getItems().stream().map(item -> {
                WareSkuLockVo.WareOrder wareOrder = new WareSkuLockVo.WareOrder();
                wareOrder.setSkuId(item.getSkuId().toString());
                wareOrder.setCount(item.getSkuQuantity());
                wareOrder.setTitle(item.getSkuName());
                return wareOrder;
            }).collect(Collectors.toList());
            lockVo.setLocks(collect);
            R r = wmsFeignService.orderLockStock(lockVo);
            if(r.getCode() != 0){
                throw new WareStockException(lockVo.getOrderSn());
            }
            respVo.setOrder(to.getOrder());
            respVo.setCode(0);
            //int  i = 1/0;
            rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",to.getOrder());
            return respVo;
        }
    }

    @Transactional
    @Override
    public void closeOrder(OrderEntity entity) {
        OrderEntity byId = this.getById(entity.getId());
        if(byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity closeEntity = new OrderEntity();
            closeEntity.setId(entity.getId());
            closeEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(closeEntity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity,orderTo);
            System.out.println("发送库存服务---开始解锁库存");
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity entity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        PayVo payVo = new PayVo();
        BigDecimal payAmount = entity.getPayAmount();
        //设置金额保留2位小数，并且向上取整
        BigDecimal amount = payAmount.setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(amount.toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject("景谷商城订单");
        payVo.setBody("订单请求提交");
        return payVo;
    }

    @Override
    public PageUtils orderItemList(Integer pageNum) {
        MemberResponseVo member = LoginInterceptor.loginUser.get();
        Map<String,Object> params = new HashMap<>();
        params.put("page",pageNum);
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",member.getId()).orderByDesc("id")
        );

        List<OrderEntity> records = page.getRecords();
        List<OrderEntity> order_sn = records.stream().map(item -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", item.getOrderSn()));
            item.setItemEntities(list);
            return item;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity entity = new PaymentInfoEntity();
        entity.setAlipayTradeNo(vo.getTrade_no());
        entity.setOrderSn(vo.getOut_trade_no());
        entity.setCallbackTime(vo.getNotify_time());
        entity.setPaymentStatus(vo.getTrade_status());
        paymentInfoService.save(entity);
        if(vo.getTrade_status().equals("TRADE_SUCCESS")|| vo.getTrade_status().equals("TRADE_FINISHED")) {
            OrderEntity entity1 = new OrderEntity();
            entity1.setStatus(OrderStatusEnum.PAYED.getCode());
            this.baseMapper.update(entity1, new UpdateWrapper<OrderEntity>().eq("order_sn", vo.getOut_trade_no()));
            return "success";
        }
            return null;
    }

    @Override
    public void orderSeckill(SeckillOrderTo entity) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(entity.getOrderSn());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setMemberId(entity.getMemberId());
        BigDecimal amount = entity.getSeckillPrice().multiply(new BigDecimal(entity.getNum()));
        orderEntity.setPayAmount(amount);
        this.save(orderEntity);

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(entity.getOrderSn());
        orderItemEntity.setRealAmount(amount);
        orderItemEntity.setSkuQuantity(entity.getNum());
        orderItemService.save(orderItemEntity);
    }

    private void saveOrder(OrderCreateTo to) {
        OrderEntity order = to.getOrder();
        order.setModifyTime(new Date());
        this.save(order);
        List<OrderItemEntity> items = to.getItems();
        orderItemService.saveBatch(items);
    }

    private OrderCreateTo createOrder(){
       MemberResponseVo member = LoginInterceptor.loginUser.get();
       OrderCreateTo to = new OrderCreateTo();
       //构建订单信息
       String orderSn = IdWorker.getTimeId();
       OrderEntity entity = buildOrderEntity(member);
        entity.setOrderSn(orderSn);
       //构建所有订单项信息
       List<OrderItemEntity> items =   buildOrderItems(orderSn);

       //处理价格\积分相关
       computePrice(entity,items);
       to.setItems(items);
       to.setOrder(entity);
       return to;
     }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> items) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        int  gift = 0;
        int  growth = 0;
        for (OrderItemEntity item : items) {
            total = total.add(item.getRealAmount());
            coupon = coupon.add(item.getCouponAmount());
            integration = integration.add(item.getIntegrationAmount());
            promotion = promotion.add(item.getPromotionAmount());
            gift += item.getGiftIntegration();
            growth+=item.getGiftGrowth();

        }
        entity.setPayAmount(total.add(entity.getFreightAmount()));
        entity.setCouponAmount(coupon);
        entity.setIntegrationAmount(integration);
        entity.setPromotionAmount(promotion);
        entity.setTotalAmount(total);
        entity.setIntegration(gift);
        entity.setGrowth(growth);

        entity.setDeleteStatus(0);
    }


    /**
     * 构建所有订单项信息
     * @return
     * @param orderSn
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderConfirmVo.OrderItemVo> vos = cartFeignService.OrderItemList();
        if(CollectionUtils.isNotEmpty(vos)) {
            List<OrderItemEntity> collect = vos.stream().map(vo -> {
                OrderItemEntity orderItemEntity = buildOrderItem(vo);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
       return null;
    }

    /**
     * 构建一个订单项
     * @param vo
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderConfirmVo.OrderItemVo vo) {
        OrderItemEntity item = new OrderItemEntity();
        //sku信息
        item.setSkuId(Long.parseLong(vo.getSkuId()));
        item.setSkuName(vo.getTitle());
        item.setSkuPrice(new BigDecimal(vo.getPrice().toString()));
        item.setSkuPic(vo.getImage());
        item.setSkuQuantity(vo.getCount());
        item.setSkuAttrsVals(String.join(";",vo.getSaleAttr()));
        //积分信息
        item.setGiftGrowth(vo.getPrice().multiply(new BigDecimal(vo.getCount().toString())).intValue());
        item.setGiftIntegration(vo.getPrice().multiply(new BigDecimal(vo.getCount().toString())).intValue());

        //spu信息
        R r = productFeignService.getSpuInfoBySkuId(vo.getSkuId());
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        item.setSpuId(data.getId());
        item.setSpuBrand(data.getBrandId().toString());
        item.setSpuName(data.getSpuName());
        item.setCategoryId(data.getCatalogId());

        //价格信息
        item.setIntegrationAmount(new BigDecimal("0.0"));
        item.setCouponAmount(new BigDecimal("0.0"));
        item.setPromotionAmount(new BigDecimal("0.0"));
        BigDecimal orign = item.getSkuPrice().multiply(new BigDecimal(item.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(item.getIntegrationAmount()).subtract(item.getPromotionAmount()).subtract(item.getCouponAmount());
        item.setRealAmount(subtract);
        return item;
    }

    /**
     * 构建订单信息
     * @param member
     */
    private OrderEntity buildOrderEntity(MemberResponseVo member) {
        OrderEntity entity = new OrderEntity();
        entity.setMemberId(member.getId());
        entity.setMemberUsername(member.getUsername());
        R fare = wmsFeignService.getFare(member.getId() + "");
        OrderFareVo data = fare.getData(new TypeReference<OrderFareVo>() {
        });
        entity.setFreightAmount(data.getFare());
        //设置收货人信息
        entity.setReceiverCity(data.getAddress().getCity());
        entity.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        entity.setReceiverName(data.getAddress().getName());
        entity.setReceiverPhone(data.getAddress().getPhone());
        entity.setReceiverPostCode(data.getAddress().getPostCode());
        entity.setReceiverProvince(data.getAddress().getProvince());
        entity.setReceiverRegion(data.getAddress().getRegion());

        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

}